package com.itheima.nio.tomcat.parse;

import com.itheima.nio.tomcat.exception.IsNotImplementsHttpServletException;
import com.itheima.nio.tomcat.inter.HttpServlet;
import com.itheima.nio.tomcat.inter.ParseServletConfig;
import com.itheima.nio.tomcat.inter.ServletConcurrentHashMap;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesParseServletConfig implements ParseServletConfig {
    @Override
    public void parse() {

        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("itheima-nio-tomcat\\webapp/config/servlet-info.properties"));
            String servletInfoValue = properties.getProperty("servlet-info");
            String[] uriAndClassNameStringArray = servletInfoValue.split(";");
            for (String urlAndClassName : uriAndClassNameStringArray){
                String[] uriAndClassNameArray = urlAndClassName.split(",");
                String urlPattern = uriAndClassNameArray[0];
                String fullClassName = uriAndClassNameArray[1];
                Class servletClass = Class.forName(fullClassName);
                boolean flag = false;
                Class[] interfaces = servletClass.getInterfaces();
                for (Class cla : interfaces){
                    if (cla == HttpServlet.class){
                        flag = true;
                        break;
                    }
                }
                if (flag){
                    HttpServlet httpServlet = (HttpServlet) servletClass.newInstance();
                    ServletConcurrentHashMap.concurrentHashMap.put(urlPattern, httpServlet);
                } else {
                    try{
                        throw new IsNotImplementsHttpServletException(servletClass.getName() + "---->> is not implement HttpServlet interface .....");
                    } catch (Exception e){
                        e.printStackTrace();
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
